using System;
using System.Collections.Generic;
using System.Text;
using Microsoft.SharePoint;
using System.Diagnostics;

namespace SharePointing.Features.Translation.FeatureReceivers
{
    /// <summary>
    /// This class provides the follwing when the list instances are provisioned:
    /// 1) Creation of the Lookup Site Column
    /// 2) Addition of this site column to the Translation List.
    /// 3) Wiring of the Event Receivers to the lists
    /// </summary>
    public class ListInstanceFeatureReceiver : SPFeatureReceiver
    {

        // This class performs the operations that we need to perform when the list
        // Instances feature is deployed / activated / deactivated
        #region Feature Activated
        public override void FeatureActivated(SPFeatureReceiverProperties properties)
        {
            using (SPSite site = properties.Feature.Parent as SPSite)
            {
                if (null == site)
                    return;

                SPWeb web = site.RootWeb;

                // Add the new Lookup Site Column to the root web of the site collection IF it doesn't already exist
                SPList lookuplist = web.Lists[Common.Lists.METATAGTYPELIST];
                web.Fields.AddLookup(Common.SiteColumns.METATAGLOOKUPFIELDNAME, lookuplist.ID, true);
                SPFieldLookup lookup = (SPFieldLookup) web.Fields[Common.SiteColumns.METATAGLOOKUPFIELDNAME];
                lookup.AllowMultipleValues = false;
                lookup.LookupField = Common.SiteColumns.METATAGTYPEFIELDNAME;
                lookup.Group = Common.SiteColumns.METATAGCOLUMNGROUP;
                lookup.Required = true;
                lookup.Update(true);
                web.Update();

                // Now we need to add the field link to the Content Type
                SPContentType ct = web.ContentTypes[Common.ContentTypes.METATAGCONTENTTYPE];
                // SPFieldLookup lookup = (SPFieldLookup)web.Fields[Common.SiteColumns.METATAGLOOKUPFIELDNAME];
                SPFieldLink link = new SPFieldLink((SPField)lookup);
                link.DisplayName = Common.SiteColumns.METATAGLOOKUPFIELDNAME;
                ct.FieldLinks.Add(link);
                ct.Update(true);
                web.Update();                    



                // Next, We will add the appropriate Site Column to the "Root" Content Type
                SPFieldCollection collFields = web.Fields;
                string strNewColumn = string.Empty;
                strNewColumn = collFields.Add(Common.SiteColumns.METATAGPAGETAGS, SPFieldType.Note, false);
                SPField pubfield = collFields[Common.SiteColumns.METATAGPAGETAGS];
                SPFieldLink oFieldLink = new SPFieldLink((SPField)pubfield);
                SPContentType oContentType = web.ContentTypes[Common.ContentTypes.ROOTPUBLISHINGCONTENTTYPE];
                oFieldLink.DisplayName = Common.SiteColumns.METATAGPAGETAGS;
                oContentType.FieldLinks.Add(oFieldLink);
                oContentType.Update(true);
                web.Update();
     

                // Next we need to wire up the event receiver for the lists. When the data is updated,
                // the cache needs to be cleared so we are using a receiver for this.
                SPList tagList = web.Lists[Common.Lists.METATAGLIST];
                SPList typeList = web.Lists[Common.Lists.METATAGTYPELIST];

                // remove the receivers if they are there
                int count = tagList.EventReceivers.Count;
                for (int i = count-1; i >= 0; i--)
                {
                    tagList.EventReceivers[i].Delete();
                }
                //tagList.Update();

                //tagList = web.Lists[Common.Lists.METATAGLIST];
                // now attach the event receivers
                tagList.EventReceivers.Add(SPEventReceiverType.ItemAdding, Common.Settings.ASSEMBLYNAME, Common.Settings.RECEIVERNAME);
                tagList.EventReceivers.Add(SPEventReceiverType.ItemUpdating, Common.Settings.ASSEMBLYNAME, Common.Settings.RECEIVERNAME);
                tagList.EventReceivers.Add(SPEventReceiverType.ItemDeleting, Common.Settings.ASSEMBLYNAME, Common.Settings.RECEIVERNAME);
                //tagList.Update();

                // remove the receivers if they are there
                count = typeList.EventReceivers.Count;
                for (int i = count - 1; i >= 0; i--)
                {
                    typeList.EventReceivers[i].Delete();
                }
                //typeList.Update();

                //typeList = web.Lists[Common.Lists.METATAGTYPELIST];
                // now attach the event receivers
                typeList.EventReceivers.Add(SPEventReceiverType.ItemAdding, Common.Settings.ASSEMBLYNAME, Common.Settings.RECEIVERNAME);
                typeList.EventReceivers.Add(SPEventReceiverType.ItemUpdating, Common.Settings.ASSEMBLYNAME, Common.Settings.RECEIVERNAME);
                typeList.EventReceivers.Add(SPEventReceiverType.ItemDeleting, Common.Settings.ASSEMBLYNAME, Common.Settings.RECEIVERNAME);
                //typeList.Update();

                web.Update();
            }
        }
        #endregion

        #region FeatureDeactivating
        /// <summary>
        /// Do I need to clean up the Content Type First ? If so, it would go here.
        /// </summary>
        /// <param name="properties"></param>
        public override void FeatureDeactivating(SPFeatureReceiverProperties properties)
        {
            // We need to delete the MetaTags and MetaTagType Lists if they still exist
            using (SPSite site = properties.Feature.Parent as SPSite)
            {
                if (null == site)
                    return;
                SPWeb web = site.RootWeb;

                // Delete the lists if they exist
                SPList list = web.Lists[Common.Lists.METATAGLIST];
                SPList typelist = web.Lists[Common.Lists.METATAGTYPELIST];
 
                try{list.Delete();}
                catch (Exception ex)
                {
                    // TODO: Add Appropriate Error Tracking Logic Here
                }
                try{typelist.Delete();}
                catch (Exception ex)
                {
                    // TODO: Add Appropriate Error Tracking Logic Here
                }
                //web.Update();

                // Now we will remove the Site Column that we added to the "Root" Content Type
                SPContentType pubct = web.ContentTypes[Common.ContentTypes.ROOTPUBLISHINGCONTENTTYPE];
                Guid linkId = new Guid();
                foreach(SPFieldLink link in pubct.FieldLinks)
                {
                    // Find the one we need to remove from the Content Type... direct by name didn't seem to work
                    if(link.DisplayName == Common.SiteColumns.METATAGPAGETAGS)
                    {
                        linkId = link.Id;
                    }
                }
                try
                {
                    pubct.FieldLinks.Delete(linkId);
                    pubct.Update(true);                    
                }
                catch(Exception ex)
                {
                    // TODO: You know what to do here :-)
                }
                //web.Update();

                // Now we will remove the Site Column that we added to the MetaTag Content Type
                SPContentType mtct = web.ContentTypes[Common.ContentTypes.METATAGCONTENTTYPE];
                Guid ctId = new Guid();
                foreach (SPFieldLink link in mtct.FieldLinks)
                {
                    // Find the one we need to remove from the Content Type... direct by name didn't seem to work
                    if (link.DisplayName == Common.SiteColumns.METATAGLOOKUPFIELDNAME)
                    {
                        ctId = link.Id;
                    }
                }
                try
                {
                    mtct.FieldLinks.Delete(ctId);
                    mtct.Update(true);
                }
                catch (Exception ex)
                {
                    // TODO: You know what to do here :-)
                }

                // Delete the SiteColumn for the lookup that we added previously (changed it to grab the field first and then use the internal name in case it's different ???0
                // This still does not work. Need to debug so we dont have a manual step.
                SPField luField = web.Fields.GetField(Common.SiteColumns.METATAGLOOKUPFIELDNAME);
                string internalName = luField.InternalName;
                try { web.Fields.Delete(internalName); }
                catch (Exception ex)
                {
                    // I KNOW THIS IS FAILING TO REMOVE THE SITE COLUMN
                    // TODO: Add Appropriate Error Tracking Logic Here
                }
                web.Update();
            }
        }
        #endregion
        #region FeatureInstalling
        public override void FeatureInstalled(SPFeatureReceiverProperties properties)
        {
        }
        #endregion
        #region Feature Uninstalling
        public override void FeatureUninstalling(SPFeatureReceiverProperties properties)
        {
        }
        #endregion

        #region Helper Methods

        public static SPFieldLookup CreateLookupField(string fieldName, string group, bool required, bool allowMultipleValues, SPWeb w, SPList lookupList, string lookupField)
        {
            w.Fields.AddLookup(fieldName, lookupList.ID, lookupList.ParentWeb.ID, required);
            SPFieldLookup lookup = (SPFieldLookup)w.Fields[fieldName];
            lookup.AllowMultipleValues = allowMultipleValues;
            lookup.LookupField = lookupField;
            lookup.Group = group;
            lookup.Update(true);
            return lookup;
        }

        public static void LinkFieldToContentType(SPWeb web, string contentType, SPField field)
        {
            SPContentType ct = web.ContentTypes[contentType];
            ct.FieldLinks.Add(new SPFieldLink(field));
            ct.Update();
        }
        #endregion
    }

}
